//
//  AppDelegate.m
//  百车易车险
//
//  Created by chenxu on 15/3/7.
//  Copyright (c) 2015年 chenxu. All rights reserved.
//

#import "AppDelegate.h"
#import "rootViewController.h"
#import "BPush.h"
#import "User.h"
#import "NetBaiduManager.h"
#import "NetAPIManager.h"
#import "BConnector.h"
#import "AlipayHeader.h"
#import <SMS_SDK/SMS_SDK.h>
@interface AppDelegate () <BPushDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // iOS8 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else
    {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    
    NSLog(kAPIkey_ios_self);
    NSLog(@"\n");
    NSLog(kAPIkey_ios);

    
    //每次修改生产状态要改：
    //      1.这里
    //      2.profile
    //      3.Bconnector 消息体的状态
    [BPush registerChannel:launchOptions apiKey:kAPIkey_ios_self pushMode:BPushModeProduction isDebug:NO];
   
    //上线 AppStore 时需要修改 pushMode
    [BPush setDelegate:self];
    [application setApplicationIconBadgeNumber:0];
    //[BPush setDelegate:self];

    
    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    NSLog(@"userinfo:%@",userInfo);
    if (userInfo) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"newmsg" object:userInfo];
        [BPush handleNotification:userInfo];
    }

    //统一外观
    [self customizeInterface];
    
    
    [self debug];
    //sharesdk
    [SMS_SDK registerApp:kShare_key withSecret:kShare_secret];
    return YES;
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //register to receive notifications
    [application registerForRemoteNotifications];
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"test:%@",deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannel];
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
    
    NSLog(@"Failed to get token, error: %@", error);
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    NSLog(@"%@",userInfo);
    if (application.applicationState == UIApplicationStateActive) {

    }
    [application setApplicationIconBadgeNumber:0];
    
    application.applicationIconBadgeNumber = [[userInfo valueForKeyPath:@"aps.badge"]integerValue];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"newmsg" object:userInfo];
    [BPush handleNotification:userInfo];
    
    
    
    
  
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    //如果极简 SDK 不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给 SDK if ([url.host isEqualToString:@"safepay"]) {
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"result = %@",resultDic);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"alipay" object:resultDic];

    }];
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            [[NSNotificationCenter defaultCenter]postNotificationName:@"alipay" object:resultDic];

        }];
    }

    return YES;
}

- (void) onMethod:(NSString*)method response:(NSDictionary*)data {
    NSLog(@"On method:%@", method);
    NSLog(@"data:%@", [data description]);
    NSDictionary* res = [[NSDictionary alloc] initWithDictionary:data] ;
    if ([BPushRequestMethodBind isEqualToString:method]) {
        int returnCode = [[res valueForKey:BPushRequestErrorCodeKey] intValue];
        //返回值
        if (returnCode == 0) {
            NSLog(@"绑定成功");
        
        }
    }
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)setupRootViewController{
    rootViewController *rootVC = [[rootViewController alloc] init];
    [self.window setRootViewController:rootVC];
}

- (void)customizeInterface{
    [[UISegmentedControl appearance] setTintColor:kColorTheme];
    [[UIApplication sharedApplication] setStatusBarStyle : UIStatusBarStyleLightContent ] ;
    [[UITextField appearance]setTintColor:kColorTheme];
    [[UITextView appearance]setTintColor:kColorTheme];

}

- (void)debug{
//    NSDictionary* temp =  @{
//                            @"Businessname" : @"rrrrrr",
//                            };
//    
//    [[NetAPIManager sharedManager]company_Logout_WithParams:temp andBlock:^(id data, NSError *error) {
//        
//    }];
    
    //    [[NetAPIManager sharedManager]company_request_unfinishedorder:nil andBlock:^(id data, NSError *error) {
    //        
    //    }];
    
//         temp  = @{@"username":@"a"};
//    
//        [[NetAPIManager sharedManager]request_Logout_WithParams:temp andBlock:^(id data, NSError *error) {
//    
//        }];
    
}
@end
